package org.lanqiao.util;


import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
/**
 * @Class：BaiDuMapUtil
 * @Description: //TODO
 * @auther: 刘金渝
 * @date: 2019/6/11 22:24
 *
 */


public class BaiDuMapUtil {
    public static String AK="dBQ0dQqN2nYLbGzio2wAjswS0Lvksx6u";
    //百度ak
    /**
     * @Author 刘金渝
     * @Description //TODO
     * @Date 2019/6/11 22:26
     * @Param [ip]
     * @explain       根据经纬度获取详细地址
     * @return java.lang.String
     */

    public static String getAddress(String ip) throws IOException {
        // 创建默认http连接
        HttpClient client = HttpClients.createDefault();
        // 创建一个post请求
        HttpPost post = new HttpPost("http://api.map.baidu.com/geocoder/v2/");
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        //传递的参数
        paramList.add(new BasicNameValuePair("ak", AK));
//        paramList.add(new BasicNameValuePair("sn", ""));
        // 传递的参数
        paramList.add(new BasicNameValuePair("location", ip));
        // 把参转码后放入请求实体中
        HttpEntity entitya = new UrlEncodedFormEntity(paramList, "utf-8");
        // 把请求实体放post请求中
        post.setEntity(entitya);
        // 用http连接去执行get请求并且获得http响应
        HttpResponse response = client.execute(post);
        // 从response中取到响实体
        HttpEntity entity = response.getEntity();
        // 把响应实体转成文本
        String html = EntityUtils.toString(entity);
        String advice=null;
        try {
            JSONObject jsonObject = xml2JSON(html.getBytes());
            String s = jsonObject.toJSONString();
            advice = getAdvice(s);
            return  advice;

        } catch (JDOMException e) {
            e.printStackTrace();
        }
        return  advice;
    }

    public static String getAdvice(String resultStr) {
        JsonParser jp = new JsonParser();
        //将json字符串转化成json对象
        JsonObject jo = jp.parse(resultStr).getAsJsonObject();

        //获取城市对应的值
        String city = jo.get("GeocoderSearchResponse").getAsJsonObject().get("result").getAsJsonArray().get(0).getAsJsonObject()
                .get("addressComponent").getAsJsonArray().get(0).getAsJsonObject().get("city").getAsString();
        String district = jo.get("GeocoderSearchResponse").getAsJsonObject().get("result").getAsJsonArray().get(0).getAsJsonObject()
                .get("addressComponent").getAsJsonArray().get(0).getAsJsonObject().get("district").getAsString();
        String address = jo.get("GeocoderSearchResponse").getAsJsonObject().get("result").getAsJsonArray().get(0).getAsJsonObject()
                .get("poiRegions").getAsJsonArray().get(0).getAsJsonObject().get("poiRegion").getAsJsonArray().get(0).getAsJsonObject().get("name").getAsString();

        return city+district+address;
    }


    /**
     * @return com.alibaba.fastjson.JSONObject
     * @Author 刘金渝
     * @Description //TODO
     * @Date 2019/6/10 16:34
     * @Param [xml]
     * @explain 将xml转换城json
     */

    public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        org.jdom2.Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new LinkedList();
            et = (Element) node.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0) {
                    continue;
                }
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }



}
